package com.activenetwork.util.grid.gson;

import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.activenetwork.util.grid.DataGrid;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.google.gson.Gson;

public class GridFactory {
	private static Logger logger = LoggerFactory.getLogger(GridFactory.class);
	private static GridLookup lookup ;
	
	private static void bind() throws IOException{
		Gson gson = new Gson();
		String json = Resources.toString(Resources.getResource("Datagrid.json"), Charsets.UTF_8);		
		lookup = gson.fromJson(json, GridLookup.class);
	}
	
	public static DataGrid getGrid(String pageName, String gridName){
		if(lookup == null){
			try {
				bind();
			} catch (IOException e) {				
				throw new RuntimeException("I/O exception occurred for Datagrid.json");
			}
		}
		
		// find the specific grid
		GridDetail target = null;
		List<GridDetail> grids = lookup.getGrids();
		for(GridDetail grid : grids){
			String gname = grid.getGridName();
			String pname = grid.getPageName();
			if(StringUtils.equals(pageName, pname) && StringUtils.equals(gridName, gname)){
				logger.trace("Page:" + pname + " - Grid:" + gname);
				target = grid;
				break;
			}
		}
		
		if(target == null){
			throw new RuntimeException("Unable to find the grid in json:" + gridName);
		}
		
		GridDescriber describer = target.getGridDesc();

		By tbodyBy = createBy(describer.getTbody());
		By theadBy = createBy(describer.getThead());
		By paginationBy = createBy(describer.getPagination());
		By filterBy = createBy(describer.getFilter());
		By pageSizeBy = createBy(describer.getPageSize());
		
		return new DataGrid(tbodyBy, theadBy, paginationBy, filterBy, pageSizeBy);
	}
	
	private static By createBy(GridSelector by){
		String css = by.getCss();
		String xpath = by.getXpath();
		
		if(css != null && css.length() > 0 ){
			logger.trace(css);
			return By.cssSelector(css);
		}
		
		if(xpath != null && xpath.length() > 0){
			logger.trace(xpath);
			return By.xpath(xpath);
		}
		
		return null;
		
	}
	

}
